/*!
 * Page: pages/theme/新建文件夹/新建文件夹
 * License: MIT
 * Created: 2019-11-08 10:51
 */

import { feedApi } from '/api/feed'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    list: [] as DomoTheme[],
    isLastpage: false,
    advertisingList: [] as any,
  },
  async onLoad() {
    this.getThemeList()
    $event.on('editorTheme', this, (theme: DomoTheme) => {
      const list = this.data.list
      list[list.findIndex((item) => item.id === +theme.id)] = theme
      this.setData({
        list,
      })
    })
    $event.on('after:deleteTheme', this, (theme: DomoTheme) => {
      const list = this.data.list
      list.splice(
        list.findIndex((item) => item.id === theme.id),
        1,
      )
      this.setData({
        list,
      })
    })
    this.setData({
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  onShow() { },
  async onPullDownRefresh() {
    this.setData({
      list: [],
      isLastpage: false,
    })
    await this.getThemeList()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    this.getThemeList()
  },
  async getThemeList() {
    if (this.data.isLastpage) {
      wx.showToast({
        title: '已没有更多数据',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (this.data.list.length > 0) {
      wx.showLoading({
        title: '加载中',
      })
    }

    const list = await feedApi.getThemeList({
      after: this.data.list.length > 0 ? this.data.list[this.data.list.length - 1].id : '',
    })
    const isLastpage = list.length < 15
    this.setData({ list: [...this.data.list, ...list], isLastpage })
    wx.hideLoading()
  },
  themeDetail(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/theme/detail/detail?id=${id}`,
    })
  },
  /** 广告话题详情 */
  advertisingThemeDetail(e: WechatMiniprogram.BaseEvent) {
    const info = e.currentTarget.dataset.item.data.link
    const title = info.split(':')[1]
    wx.navigateTo({
      url: `/pages/theme/detail/detail?id=${title}`,
    })
  },
  /**
   * 搜索话题
   */
  goSearchTopic() {
    wx.navigateTo({
      url: `/mall/search/search?index=${8}`,
    })
  },
})
